package com.my.ext.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.my.ext.entity.User;
import com.my.ext.mapper.UserMapper;
import com.my.ext.service.IUserService;
import com.my.ext.utils.HttpClientUtils;
import com.my.ext.utils.StaticContent;

@Service
public class UserService implements IUserService{

	@Autowired
	UserMapper mapper;
	
	public User authWX(String code) {
		Map<String, String> result = new HashMap<>();
		Map<String, String> map = getWXAuth(code);
		System.out.println(map.get("openid"));
		User u = mapper.findUser(map.get("openid"));
		if(u == null) {
			u = new User();
			u.setOpenid(map.get("openid"));
		} else {
			mapper.updateSessionKey(map.get("openid"), map.get("session_key"));
		}
		return u;
	}

	@Override
	public int updateUser(int org, int group, String name, String code, String openid) {
		return mapper.updateUser(org, group, name, code, openid);
	}
	
	public Map<String, String> getWXAuth(String code) {
		Map<String, String> param = new HashMap<>();
		param.put("appid", StaticContent.APP_ID);
		param.put("secret", StaticContent.APP_SEC);
		param.put("js_code", code);
		param.put("grant_type", "authorization_code");
		String str = HttpClientUtils.doHttpGet("https://api.weixin.qq.com/sns/jscode2session", param);
		JSONObject jsonObject = JSONObject.parseObject(str);
		Map<String, String> result = new HashMap<>();
		result.put("openid", jsonObject.getString("openid"));
		result.put("session_key", jsonObject.getString("session_key"));
		return result;
	}

	@Override
	public User getUserByOpenid(String openid) {
		return mapper.findUser(openid);
	}
	
}
